﻿using System.Transactions;
using System.Web;

namespace Skyhook.TransactionControl.Objects {
    public class TransactionManager {
        public static CommittableTransaction Get() {
            if (HttpContext.Current != null && HttpContext.Current.Session != null)
                if (HttpContext.Current.Session["TransactionManager"] != null)
                    return (CommittableTransaction)HttpContext.Current.Session["TransactionManager"];
                else {
                    var transaction = new CommittableTransaction();
                    HttpContext.Current.Session["TransactionManager"] = transaction;
                    return transaction;
                }
            else {
                if (TransactionLocal.Transaction != null)
                    return TransactionLocal.Transaction;
                else {
                    var transaction = new CommittableTransaction();
                    TransactionLocal.Transaction = transaction;
                    return transaction;
                }
            }
        }

        public static void Rollback() {
            var transaction = Get();
            transaction.Rollback();
            RemoveSessionVariables();
        }
        public static void Commit() {
            var transaction = Get();
            var connection = DataAccess.GetConnection();
            connection.Close();
            transaction.Commit();
            RemoveSessionVariables();
        }

        private static void RemoveSessionVariables() {
            if (HttpContext.Current != null && HttpContext.Current.Session != null) {
                HttpContext.Current.Session.Remove("TransactionManager");
                HttpContext.Current.Session.Remove("SqlConnection");
            }
            else {
                TransactionLocal.Transaction = null;
                SqlConnectionLocal.Connection = null;
            }
        }
    }

    internal static class TransactionLocal {
        public static CommittableTransaction Transaction;
    }
}
